package com.ruleengine.executer.impl;

import org.apache.log4j.Logger;

import com.ruleengine.context.IWorkflowConext;
import com.ruleengine.endpoint.IEndpoint;
import com.ruleengine.endpoint.IEndpointFactory;
import com.ruleengine.endpoint.callback.impl.DefaultEndpointCallback;
import com.ruleengine.endpoint.configration.EndpointManager;
import com.ruleengine.endpoint.data.IEndpointData;
import com.ruleengine.executer.InstructionExecuter;
import com.ruleengine.executer.exception.InstructionExecuteException;
import com.ruleengine.instruction.impl.InvokerInstruction;

public class InvokerInstructionExecuter implements
        InstructionExecuter<InvokerInstruction> {
    private static Logger logger = Logger
            .getLogger(InvokerInstructionExecuter.class);

    /*
     * (non-Javadoc)
     * 
     * @see com.wx.workflow.engine.invoker.InstructionExecuter#execute(com.wx.workflow.engine.context.IWorkflowConext,
     *      com.wx.workflow.engine.message.IWorkflowData,
     *      com.wx.workflow.engine.instruction.Instruction)
     */
    public boolean execute(IWorkflowConext context, IEndpointData data,
            InvokerInstruction instruction) throws InstructionExecuteException {
        // TODO Auto-generated method stub
        try {
            // 获取接出节点的的工厂
            IEndpointFactory factory = EndpointManager.getInstance()
                    .createEndpointFactory(instruction.getInvokerType());
            // 获取接出节点
            IEndpoint point = factory.createEndpoint(instruction.getTarget());
            // 执行接出节点
            if(instruction.isSynchronize()){
                //同步调用
                point.send(context, data);
            }else{
                //异步调用
                DefaultEndpointCallback back = new DefaultEndpointCallback(context, data);
                point.sendNonBlocking(context, data, back);
            }
            return true;
        } catch (Exception e) {
            throw new InstructionExecuteException(e);
        }
    }

}
